package com.code.coinprice.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.code.coinprice.mappers.CoinPriceSourceRouteMapper;
import com.code.coinprice.models.CoinPriceSource;
import com.code.coinprice.models.CoinPriceSourceRoute;
import com.code.coinprice.services.CoinPriceSourceRouteService;
import com.code.coinprice.services.CoinPriceSourceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CoinPriceSourceRouteServiceImpl implements CoinPriceSourceRouteService {

    @Resource
    private CoinPriceSourceRouteMapper coinPriceSourceRouteMapper;

    @Resource
    private CoinPriceSourceService coinPriceSourceService;

    @Override
    public CoinPriceSource getNextCoinPriceSourceBySourceOnInvokeApiError(String source) {
        CoinPriceSource coinPriceSourceBySource = coinPriceSourceService.getCoinPriceSourceBySource(source);
        if (coinPriceSourceBySource != null) {
            int id = coinPriceSourceBySource.getId();
            QueryWrapper<CoinPriceSourceRoute> coinPriceSourceRouteWrapper = new QueryWrapper<>();
            coinPriceSourceRouteWrapper.eq("source_parent_id", id);
            CoinPriceSourceRoute coinPriceSourceRoute = coinPriceSourceRouteMapper.selectOne(coinPriceSourceRouteWrapper);
            if (coinPriceSourceRoute != null) {
                return coinPriceSourceService.getCoinPriceSourceById(coinPriceSourceRoute.getSourceId());
            }

        }
        return null;
    }

    @Override
    public List<String> getNextCoinPriceSourceListBySourceOnInvokeApiError(List<String> nextSourceList, String source) {
        CoinPriceSource nextCoinPriceSource = getNextCoinPriceSourceBySourceOnInvokeApiError(source);
        if (nextCoinPriceSource != null) {
            String nextSource = nextCoinPriceSource.getSource();
            nextSourceList.add(nextSource);
            getNextCoinPriceSourceListBySourceOnInvokeApiError(nextSourceList, nextSource);
        }
        return nextSourceList;
    }
}
